package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.bo.Service;
import edu.byu.intex2.data.bo.ServiceLine;
import edu.byu.intex2.data.bo.TradeInLine;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Service Data Access Object
 * @author Jason Whiting
 */
public class ServiceDAO
{

    /////////////////////////////////////////////
    ///   Singleton code
    private static ServiceDAO instance = null;

    /** Creates a new instance of ServiceDAO */
    private ServiceDAO()
    {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized ServiceDAO getInstance()
    {
        if (instance == null)
        {
            instance = new ServiceDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new service in the database */
    public Service create(String id) throws DataException
    {
        Service service = new Service(id);
        service.setObjectAlreadyInDB(false);
        Cache.getInstance().put(service.getId(), service);
        return service;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing service from the database     */
    public Service read(String id) throws DataException
    {
        // Check Cache
        if (Cache.getInstance().containsKey(id))
        {
            return (Service) Cache.getInstance().get(id);
        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try
        {
            return read(id, conn);
        } catch (Exception e)
        {
            throw new DataException("An error occurred while reading the business object information.", e);
        } finally
        {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing service from the database
     * @return service
     */
    synchronized Service read(String id, Connection conn) throws Exception
    {
        // Check Cache
        if (Cache.getInstance().containsKey(id))
        {
            return (Service) Cache.getInstance().get(id);
        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM service where id=?");

        try
        {
            stmt.setString(1, id);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next())
            {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("Service with id '" + id + "' not found.");
        } finally
        {
            stmt.close();
        }
    }//read

    /** Internal method to create a service object from a record  */
    synchronized Service readRecord(ResultSet rs, Connection conn) throws Exception
    {
        if (Cache.getInstance().containsKey(rs.getString("id")))
        {
            return (Service) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new service object
        Service service = new Service(rs.getString("id"));

        // Service is already in DB
        service.setObjectAlreadyInDB(true);

        // Put service in cache
        Cache.getInstance().put(service.getId(), service);

        // Set Service Attributes
        service.setDate(rs.getDate("service_date"));
        service.setTotalPrice(rs.getDouble("total_price"));
        service.setTax(rs.getDouble("tax"));
        service.setServiceFacilityId(rs.getString("service_facility_id"));
        service.setTechnicianId(rs.getString("technician_id"));
        service.setCustomerId(rs.getString("customer_id"));
        service.setPhysicalCarId(rs.getString("physical_car_id"));

        // Service is dirty and needs to be saved to DB
        service.setDirty(false);

        return service;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing service in the database */
    public void save(Service service) throws DataException
    {
        // get a connection from the pool, save all of the services first using the other service method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try
        {
            save(service, conn); // save with connection
            conn.commit();  // commit the db transaction
            service.setObjectAlreadyInDB(true); // service is now in DB
        } catch (Exception e)
        {
            try
            {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2)
            {
                throw new DataException("Could not roll back the service database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the service object information.", e);
        } finally
        {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a service in the database */
    void save(Service service, Connection conn) throws Exception
    {
        // put the service object to cache
        Cache.getInstance().put(service.getId(), service);

        // decide whether to update or insert into the database
        if (service.isObjectAlreadyInDB() && service.isDirty())
        {
            update(service, conn);
        } else if (service.isDirty())
        {
            insert(service, conn);
        }//if

        // Save service lines
        List<ServiceLine> serviceLines = service.getServiceLines();
        for (ServiceLine sl : serviceLines)
        {
            ServiceLineDAO.getInstance().saveNoCommit(sl, conn);
        }
    }

    /** External method to update or create a service in the database without committing connection */
    public void saveNoCommit(Service service, Connection conn, Boolean alreadyInDB) throws Exception
    {
        // decide whether to update or insert into the database
        if (alreadyInDB)
        {
            update(service, conn);
        } else
        {
            insert(service, conn);
        }
    }

    /** Saves an existing service to the database */
    private void update(Service service, Connection conn) throws Exception
    {
        // use a prepared statement to prevent sql injection
        PreparedStatement stmt = conn.prepareStatement("UPDATE service SET service_date=?, total_price=?, tax=?, service_facility_id=?, technician_id=?, customer_id=?, physical_car_id=?  WHERE id=?");
        try
        {
            // Get Service Attributes and add them to the statement
            stmt.setDate(1, new java.sql.Date(service.getDate().getTime()));
            stmt.setDouble(2, service.getTotalPrice());
            stmt.setDouble(3, service.getTax());
            stmt.setString(4, service.getServiceFacilityId());
            stmt.setString(5, service.getTechnicianId());
            stmt.setString(6, service.getCustomerId());
            stmt.setString(7, service.getPhysicalCarId());
            stmt.setString(8, service.getId());
            stmt.execute();

            // Service is clean!
            service.setDirty(false);
        } finally
        {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new service into the database */
    private void insert(Service service, Connection conn) throws Exception
    {
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO service (id, service_date, total_price, tax, service_facility_id, technician_id, customer_id, physical_car_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        try
        {
            // Set Service Attributes
            stmt.setString(1, service.getId());
            stmt.setDate(2, new java.sql.Date(service.getDate().getTime()));
            stmt.setDouble(3, service.getTotalPrice());
            stmt.setDouble(4, service.getTax());
            stmt.setString(5, service.getServiceFacilityId());
            stmt.setString(6, service.getTechnicianId());
            stmt.setString(7, service.getCustomerId());
            stmt.setString(8, service.getPhysicalCarId());
            stmt.execute();

            service.setObjectAlreadyInDB(true); // now in DB
            service.setDirty(false); // object is clean
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(Service service) throws DataException
    {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }
}
